package cc.vv.party.service.impl;

import cc.vv.party.beans.model.OrgAdmin
import cc.vv.party.beans.model.PmcAccountor
import cc.vv.party.common.base.BaseServiceImpl
import cc.vv.party.common.constants.StatusCode
import cc.vv.party.exception.BizException
import cc.vv.party.mapper.PmcAccountorMapper
import cc.vv.party.service.OrgAdminService
import cc.vv.party.service.PmcAccountorService
import com.baomidou.mybatisplus.mapper.EntityWrapper
import commonx.core.content.isNotNullOrEmpty
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Gyb
 * @since 2018-11-07
 */
@Service
open class PmcAccountorServiceImpl : BaseServiceImpl<PmcAccountorMapper, PmcAccountor>(), PmcAccountorService {

    @Autowired
    lateinit var orgAdminService: OrgAdminService

    override fun checkAccountExists(account: String, orgId: String?) {
        if (orgId.isNotNullOrEmpty()) {
            //编辑组织机构信息
            val count =
                orgAdminService.selectCount(EntityWrapper<OrgAdmin>().ne("org_id", orgId).eq("user_account", account))
            if (count > 0) {
                throw BizException(StatusCode.ERROR.statusCode, "管理员${account}已经存在")
            }
        } else {
            //新增
            val count =
                orgAdminService.selectCount(EntityWrapper<OrgAdmin>().eq("user_account", account))
            if (count > 0) {
                throw BizException(StatusCode.ERROR.statusCode, "管理员${account}已经存在")
            }
        }
        selectOne(EntityWrapper<PmcAccountor>().eq("account", account))
            ?: throw BizException(StatusCode.LOGIN_PASSWORD_ERROR.statusCode, "该账号在延安党建中不存在，请查证")
    }

    override fun checkPmcAccountExists(account: String) {
        selectOne(EntityWrapper<PmcAccountor>().eq("account", account))
            ?: throw BizException(StatusCode.LOGIN_PASSWORD_ERROR.statusCode, "该账号在延安党建中不存在，请查证")
    }


    override fun checkAccountListExists(accountList: List<String>) {
        if (accountList.isEmpty()) {
            throw BizException(
                StatusCode.LOGIN_PASSWORD_ERROR.statusCode,
                "参数不能为空"
            )
        }
        val list = selectList(EntityWrapper<PmcAccountor>().`in`("account", accountList))?.map { it.id!! }
        if (list == null || list.isEmpty()) {
            throw BizException(
                StatusCode.LOGIN_PASSWORD_ERROR.statusCode,
                "账号${accountList.joinToString(separator = ",")}在延安党建中不存在，请查证"
            )
        }

        if (list.size != accountList.size) {
            accountList.forEach {
                if (!list.contains(it)) throw BizException(
                    StatusCode.LOGIN_PASSWORD_ERROR.statusCode,
                    "账号${it}在延安党建中不存在，请查证"
                )
            }
        }
    }
}
